﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;


namespace Common
{
    public class BytesConvert
    {
        public static byte[] StructToBytes(object structObj)
        {
            int size = Marshal.SizeOf(structObj);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.StructureToPtr(structObj, buffer, false);
                byte[] bytes = new byte[size];
                Marshal.Copy(buffer, bytes, 0, size);
                return bytes;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }

        }

        public static object BytesToStruct(byte[] bytes, Type strcutType)
        {
            int size = Marshal.SizeOf(strcutType);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.Copy(bytes, 0, buffer, size);
                return Marshal.PtrToStructure(buffer, strcutType);
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }

        public static byte[] ObjectToBytes<T>(T obj)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    formatter.Serialize(ms, obj);
                    return ms.GetBuffer();
                }
            }
            catch (Exception ex)
            {
                //throw ex;
                return null;
            }
        }

        public static byte[] ObjectToBytes<T>(T obj, bool isCompress)
        {
            if (!isCompress)
            {
                return ObjectToBytes<T>(obj);
            }
            else
            {
                try
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        formatter.Serialize(ms, obj);
                        MemoryStream tempms = new MemoryStream();
                        System.IO.Compression.GZipStream gzs = new System.IO.Compression.GZipStream(tempms, System.IO.Compression.CompressionMode.Compress, true);
                        //ms.WriteTo(gzs);
                        byte[] arrByte = ms.GetBuffer();
                        //ms.Read(arrByte, 0, arrByte.Length);
                        gzs.Write(arrByte, 0, arrByte.Length);
                        gzs.Close();
                        gzs.Dispose();
                        return tempms.ToArray();
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

        }

        /// <summary>
        /// 将一个序列化后的byte[]数组还原
        /// </summary>
        /// <param name="Bytes"></param>
        /// <returns></returns>
        public static T BytesToObject<T>(byte[] arrBytes)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream(arrBytes))
                {
                    System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    object obj = formatter.Deserialize(ms);
                    T t = (T)obj;
                    return t;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 将byte数组转换为对象，，如果数据是压缩数据，那么isCompress必须为true
        /// </summary>
        /// <typeparam name="T">对象的类型</typeparam>
        /// <param name="arrBytes">要转换的数组</param>
        /// <param name="isCompress">数据有没有压缩过</param>
        /// <returns>byte数组转换后的类对象</returns>
        public static T BytesToObject<T>(byte[] arrBytes, bool isCompress)
        {
            if (!isCompress)
            {
                return BytesToObject<T>(arrBytes);
            }
            else
            {
                try
                {
                    //FileStream fs = new FileStream(sPriceFile, System.IO.FileMode.Open, FileAccess.Read, FileShare.Read);
                    //System.IO.Compression.GZipStream gzs = new System.IO.Compression.GZipStream(fs, System.IO.Compression.CompressionMode.Decompress);
                    //byte[] arrByteDecompress = Decompress(arrBytes);
                    using (MemoryStream ms = new MemoryStream(arrBytes))
                    {
                        //MemoryStream tempms = new MemoryStream();
                        //System.IO.Compression.GZipStream gzs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress);
                        //gzs.CopyTo(tempms);
                        //gzs.Close();
                        //tempms.Position = 0;
                        System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        object obj = formatter.Deserialize(ms);
                        T t = (T)obj;
                        return t;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
    }
}
